package io.hilo.example.app;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import org.hilo.boot.app.config.BaseFilterConfig;

/**
 * 统一配置应用的Filter及顺序
 */
@Component
public class AppFilterConfig implements BaseFilterConfig {

    /**
     * （CORS）前后端分离项目，允许前端跨域请求
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterRegistration() {
        CorsConfiguration config = new CorsConfiguration();
        // DefaultValues：
        config.addAllowedMethod(CorsConfiguration.ALL);
        config.applyPermitDefaultValues();

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 拦截的URL
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<CorsFilter>(new CorsFilter(source));
        bean.setName("App_CorsFilter");
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }
    

}
